import store from '@/store/index.js'
import {
	wsBaseUrl
} from "./baseUrl.js";
import {
	getChatMessageDetail,
	getChatMessageList
} from "@/api/message.js"

// 全局WebSocket对象
let socketTask = null;
// 心跳定时器
let heartTimer = null;
// 是否已连接
let heartbeatTimeout = 30000;
let reconnectTimeout = 5000;
let pingData = JSON.stringify({
	reqMsgType: 0,
	content: 'PING'
});
// 连接WebSocket
function connectWebSocket() {

	socketTask = uni.connectSocket({
		url: wsBaseUrl + '/ws?token=' + store.state.vuex_user.token,
		fail() {
			// console.log('调用WebSocketApi失败');
			store.state.vuex_ws_connect = false;
			reconnectWebSocket(); // 重连WebSocket
		}
	});

	// 监听WebSocket打开事件
	uni.onSocketOpen(function() {
		// console.log('WebSocket连接已打开');
		store.state.vuex_ws_connect = true;
		startHeartbeat(); // 开始心跳
	});

	// 监听WebSocket接收消息事件
	uni.onSocketMessage(function(res) {
		let msgData = JSON.parse(res.data)
		if (!msgData) {
			return
		}

		let type = msgData.respMsgType
		let body = msgData.body
		let userInfo = store.state.vuex_user
		if (type === 0) {
			// 心跳
			// console.log('服务器心跳正常:', body.content);
		} else if (type === 1 || type === 2) {
			// 1、用户收到自己发的消息 2、用户收到他人发的消息
			if (type === 2) {
				store.state.vuex_user_msg_list_red_tip = true
			}

			// 如果当前在聊天窗口页，则更新聊天窗口的消息
			let curChatId = store.state.vuex_chat_user_id
			if (curChatId && curChatId === body.userId) {
				const tempData = {
					id: body.id,
					msg: body.lastMsg,
					date: body.lastDate,
					sender: type === 1 ? 0 : 1
				}
				store.state.vuex_user_msg_detail.push(tempData)
			}

			// 更新消息列表
			let msgList = store.state.vuex_user_msg_list
			let isExistUser = false
			// 校验是否存在，存在更新，不存在插入
			let index = msgList.findIndex(item => item.userId === body.userId)
			if (index !== -1) {
				msgList[index] = body
				isExistUser = true
			}

			if (!isExistUser) {
				store.state.vuex_user_msg_list_refresh = true
				msgList.unshift(body);
			}

			// 排序
			msgList.sort((a, b) => {
				if (a.top > b.top) {
					return -1;
				}
				if (a.top < b.top) {
					return 1;
				}

				if (a.lastDate > b.lastDate) {
					return -1;
				}
				if (a.lastDate < b.lastDate) {
					return 1;
				}
				return 0;
			})



			// getChatMessageList({
			// 	page: 1,
			// 	limit: 10
			// }).then(res => {
			// 	let tempData = res.data.list
			// 	tempData.forEach(item => {
			// 		item.options = item.top === 1 ? options2 : options
			// 	})
			// 	store.state.vuex_user_msg_list = tempData
			// })
		}
	});

	// 监听WebSocket关闭事件
	uni.onSocketClose(function(res) {
		// console.log('WebSocket 已关闭:', res);
		store.state.vuex_ws_connect = false;
		stopHeartbeat(); // 停止心跳
		reconnectWebSocket(); // 重连WebSocket
	});

	// 监听WebSocket失败事件
	uni.onSocketError(function(res) {
		// console.log('WebSocket连接打开失败:', res);
		store.state.vuex_ws_connect = false;
		stopHeartbeat(); // 停止心跳
		reconnectWebSocket(); // WebSocket
	});
}

// 关闭WebSocket连接
function closeWebSocket() {
	if (socketTask) {
		socketTask.close();
		socketTask = null;
	}
	store.state.vuex_ws_connect = false;
	stopHeartbeat(); // 停止心跳
}

// 发送消息
function sendMessage(message) {
	if (socketTask && store.state.vuex_ws_connect) {
		// console.log("send", message);
		socketTask.send({
			data: message
		});
		return true;
	}

	store.state.vuex_ws_connect = false;
	return false;
}

// 开始心跳
function startHeartbeat() {
	stopHeartbeat();
	// console.log('发送心跳包...');
	heartTimer = setInterval(function() {
		sendMessage(pingData); // 发送心跳消息
	}, heartbeatTimeout);
}

// 停止心跳
function stopHeartbeat() {
	// console.log('停止心跳...');
	if (heartTimer) {
		clearInterval(heartTimer);
		heartTimer = null;
	}
}

// 重连WebSocket
function reconnectWebSocket() {
	if (!store.state.vuex_ws_connect && store.state.vuex_user) {
		// console.log('正在重连WebSocket...');
		setTimeout(function() {
			connectWebSocket();
		}, reconnectTimeout);
	}
}

export default {
	connectWebSocket,
	closeWebSocket,
	sendMessage
};